from flask import Flask, request, current_app


def init_common_pre(app: Flask):
    print(app.config.get("APP_NAME"))

    # ## 安装检查：初始化数据库
    with app.app_context():
        from extensions import db
        from task_app.models import JobPlan, JobEvent, User
        has_table = db.engine.dialect.has_table(db.engine.connect(), table_name='user')
        if not has_table:
            from task_app.commands import fake_user
            db.create_all()
            fake_user()
            current_app.logger.info("database inited success!")

    @app.route('/')
    def hello():
        return 'Hello World! 欢迎访问APP'

    @app.before_request
    def log_each_request():
        msg = 'invoke api->{}:{} '.format(request.method, request.path)
        if request.args:
            msg += 'args:{} '.format(request.args)
        if request.form:
            msg += 'form:{} '.format(request.form)
        if request.files:
            msg += 'files:{} '.format(request.files)
        if request.json:
            msg += 'json:{} '.format(request.json)
        app.logger.info(msg)

    @app.after_request
    def log_each_reponse(response):
        if response.is_json:
            app.logger.info('invoke api end->%s' % response.json)
        return response
